﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.IO;
using System.Text.RegularExpressions;
using System.ComponentModel;

namespace SimpleSocxs
{
    public class Item : WebControl
    {
        public string RenderName { get; set; }
        
        public string StreamID { get; set; }        
        public string Title { get; set; }
        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
            
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            //add panel title
            var title = Page.LoadControl("~/PanelTitleRender.ascx") as PanelTitleRender;
            title.Title = Title;
            Controls.Add(title);

            try
            {
                //add stream
                string streamIDs = StreamID;
                var innerContainer = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                innerContainer.Attributes["class"] = "contents";
                foreach(var id in streamIDs.Split(',').Select(_=>_.Trim()).Distinct()){
                    int streamID;
                    if (int.TryParse(id, out streamID))
                    {
                        var stream = SocxsDataStore.Current.GetStreamByID(streamID);
                        var user = SocxsDataStore.Current.GetUserByID(stream.UserID);

                        if (stream != null)
                        {
                            string renderName = RenderName;
                            //if (string.IsNullOrEmpty(renderName)) use default
                            renderName = stream.GetDefaultRenderName();

                            string renderPath = Helper.GetFileInUserAndShared(user.Name, "renders/" + renderName + ".ascx");
                            if (!string.IsNullOrEmpty(renderPath))
                            {
                                var ctrl = Page.LoadControl(renderPath) as BaseRender;

                                var converter = stream.GetConverter();

                                ctrl.DataSource = converter.ConvertFrom(stream.RawData);

                                if (ctrl != null)
                                    innerContainer.Controls.Add(ctrl);
                            }
                        }
                    }
                }
                Controls.Add(innerContainer);
            }
            catch 
            {
                //log bugs
            }
        }
    }
}
